<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:Order WebApp 訂單wifi打印
 *@param datetime 2015-05-07
 *@param author abin
 ********************/
class Orderprint extends Lang_Controller {

  public function __construct(){
    parent::__construct();
    $this->data['active']='orderprint';
    $this->load->model('orders_mdl');
  }

  //執行打印程序
  public function index(){
    if($this->data['sms_shop_status']==2){//是否開啟WIFI HTTP模式
      $usr=$this->input->get('usr');
      $sgn=$this->input->get('sgn');
      //if(!empty($usr) && !empty($sgn)){ //確定是打印機訪問.
      if(!empty($usr) && $usr==$this->data['print_imei'] && !empty($sgn)){ //確定是打印機訪問.
        $this->_modify_callback_data();//執行上次打印的結果處理
        $this->_get_print_data();
      }
    }
  }

  //檢查返回的數據是否要進行操作
  //返回:usr,ord,sgn,id,sta
  //usr:打印機或 sim卡 IMEI号码,id:訂單id,
  //sta:打印机状态（0为打印成功， 1为过热，3为缺纸卡纸等）
  private function _modify_callback_data(){
    $id=$this->input->get('id');//order id
    $sta=$this->input->get('sta');
    //成功返回上次的打印結果
    if(!empty($id) && is_numeric($id) && is_numeric($sta)){
      //重新改寫打印狀態,1,未打印,2已打印,3缺纸卡纸,4过热
      $is_print=$sta==0?2:($sta==1?4:$sta);
      $this->orders_mdl->edit_orders(array('is_print'=>$is_print),$id);
    }
  }

  //檢查是否有需要打印的訂單
  //只打印今天內的未打印訂單
  private function _get_print_data(){
    //今天
    $today_begin = date("Y-m-d 00:00:00");
    $today_end = date("Y-m-d 23:59:59");
    $today=array(
      'order_status_id'=>1,
      'is_print'=>1,
      'field'=>'add_time',
      'sort'=>'desc',
      'begin_time'=>strtotime($today_begin),
      'end_time'=>strtotime($today_end),
    );
    $query=$this->orders_mdl->get_orders($today);
    if(!empty($query) && $query->num_rows()>0){
      $row=$query->row_array();
      $print_data['id']=$row['id'];
      //查詢是否熟客
      $buy_number=$this->orders_mdl->totle_orders(array('phone'=>$row['phone'],'order_status_id'=>2));
      $item_string='';
      $this->load->model('ordersproduct_mdl');
      $products=$this->ordersproduct_mdl->get_ordersproduct(array('order_id'=>$row['id']));
      foreach ($products->result_array() as $item) {
        $item_string.=<<<EOT
{$item['name']}%%            {$item['price']}         {$item['quantity']}%%
EOT;
      }
      $order_way=$row['order_way']==1?'自取':'外送';
      $order_address=$row['order_way']==2?'外送地址：'.$row['address']:'';
      $order_time=$row['order_way']==2?'送到時間：'.$row['order_time']:'';
      $comment=!empty($row['comment'])?'備註：'.$row['comment']:'';
      $member_tag=$buy_number>1?'  *[熟客]':'';
      $message_txt='%10 '.$this->data['copyright'].'%%%00';
      $message_txt.='%%菜品        單價         數量%%';
      $message_txt.='-----------------------------';
      $message_txt.=$item_string;
      $message_txt.='-----------------------------';
      $message_txt.='%%%10【'.$order_way.'】        總計：'.$row['total'].'%%%00';
      $message_txt.='-----------------------------%%';
      $message_txt.='聯絡電話：'.$row['phone'].$member_tag.'%%';
      $message_txt.='顧客稱呼：'.$row['nickname'].'%%';
      $message_txt.=!empty($order_address)?$order_address.'%%':'';
      $message_txt.=!empty($order_time)?$order_time.'%%':'';
      $message_txt.=!empty($comment)?str_replace(PHP_EOL,'',$comment).'%%':'';
      $message_txt.='訂購時間：'.date('Y-m-d H:i',$row['add_time']).'%%';
      $message_txt.='訂單編號：'.$row['invoice_no'];

      $print_data['message_txt']=$message_txt;
      $print_data['time']=time();

      echo $this->_set_message($print_data);
    }
  }

  /**
    +----------------------------------------------------------
   * 生成传输用XML 不能多于2000字节
    +----------------------------------------------------------
   * @return string xml
    +----------------------------------------------------------
   */
  private function _set_message($data=array()){
    if(!empty($data) && is_array($data)){
      //构建dom document
      header("Content-type: text/xml; charset=GBK");
      $xml = new DOMDocument('1.0', 'GBK');
      $xml->formatOutput = true;

      $root = $xml->createElement('r');
      $root = $xml->appendChild($root);

      $xml_id = $xml->createElement('id');
      $xml_id->appendChild($xml->createTextNode($data['id']));
      $xml_id = $root->appendChild($xml_id);

      $xml_time = $xml->createElement('time');
      $xml_time->appendChild($xml->createTextNode(date('Y-m-d H:i:s',$data['time'])));
      $xml_time = $root->appendChild($xml_time);

      $xml_content = $xml->createElement('content');
      $xml_content->appendChild($xml->createTextNode($data['message_txt']));
      $xml_content = $root->appendChild($xml_content);

      $xml_setting = $xml->createElement('setting');
      $xml_setting->appendChild($xml->createTextNode('101:6|105:0'));
      $xml_setting = $root->appendChild($xml_setting);

      $xml->appendChild($root);
      echo $xml->saveXML();
    }
  }
}